const express = require('express')
const router = express.Router()
const {
	getList,
	getDetail,
	newBlog,
	updateBlog,
	delBlog
} = require('../../../../common/controller/blog')
const {
	SuccessModel,
	ErrorModel
} = require('../../../../common/model/res-model')
const loginCheck = require('../middleware/login-check')

router.get('/list', async (req, res, next) => {
	let author = req.query.author
	const keyword = req.query.keyword

	if (req.query.isadmin) {
		console.log('is admin')
		if (!req.session.username) {
			return res.json(new ErrorModel('未登录'))
		}
		author = req.session.username
	}

	const listData = await getList(author, keyword)
	res.json(new SuccessModel(listData))
})

router.get('/detail', async (req, res, next) => {
	const data = await getDetail(req.query.id)
	res.json(new SuccessModel(data))
})

router.post('/new', loginCheck, async (req, res, next) => {
	req.body.author = req.session.username
	const data = await newBlog(req.body)
	res.json(new SuccessModel(data))
})

router.post('/update', loginCheck, async (req, res, next) => {
	const result = await updateBlog(req.query.id, req.body)
	if (result) {
		res.json(new SuccessModel())
	} else {
		res.json(new ErrorModel('更新博客失败'))
	}
})

router.post('/del', loginCheck, async (req, res, next) => {
	const author = req.session.username
	const result = await delBlog(req.query.id, author)
	if (result) {
		res.json(new SuccessModel())
	} else {
		res.json(new ErrorModel('删除博客失败'))
	}
})

module.exports = router
